package com.wf.service;

import com.wf.dto.TaskDTO;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.MarshalledObject;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MyService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Transactional
    public void startProcess() {

        HashMap<String, Object> map = new HashMap<>();
        map.put("startTime", LocalDate.now());
        map.put("name", "李四");
        map.put("contractId",1);
        ProcessInstance agency = runtimeService.startProcessInstanceByKey("Agency", map);
        Task task = taskService.createTaskQuery()
                .processInstanceId(agency.getId())
                .singleResult();
        taskService.setAssignee(task.getId(), "lisi");
    }

    @Transactional
    public List<Task> getTasks(String assignee) {
        return taskService.createTaskQuery().taskAssignee(assignee).list();
    }


    public void completeTask(TaskDTO taskDTO) {

        HashMap<String, Object> map = new HashMap<>();

        map.put("approved", taskDTO.getApproval());

        taskService.complete(taskDTO.getTaskId(), map);

    }

    public   List<HistoricActivityInstance>  getHistory(String assignee) {

        List<HistoricActivityInstance> instanceList = historyService.createHistoricActivityInstanceQuery()
                .taskAssignee(assignee)
                .finished()
                .list();

        return instanceList;

    }
}